package org.csu.jpetstore_users_backend_pj.controller;

import jakarta.validation.Valid;
import org.csu.jpetstore_users_backend_pj.result.CommonResponse;
import org.csu.jpetstore_users_backend_pj.result.ResponseCode;
import org.csu.jpetstore_users_backend_pj.service.AccountService;
import org.csu.jpetstore_users_backend_pj.vo.AccountVO;
import org.csu.jpetstore_users_backend_pj.util.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping
@CrossOrigin(origins = "http://localhost:5173", methods = {RequestMethod.GET, RequestMethod.PUT, RequestMethod.OPTIONS, RequestMethod.POST, RequestMethod.PATCH})
public class AccountController {
    @Autowired
    private AccountService accountService;
    @Autowired
    private EncryptUtil encryptUtil;

    @PutMapping("/accounts")
    public CommonResponse editAccount(@RequestBody AccountVO formData) {
        String bn = accountService.getBannerName(formData.getFavouriteCategoryId());
        formData.setBannerName(bn);
        accountService.updateAccount(formData);
        return CommonResponse.createForSuccess(ResponseCode.UserEditSuccess.getCode(),ResponseCode.UserEditSuccess.getDescription());
    }
    @GetMapping("/accounts")
    public CommonResponse editAccountForm(@RequestParam String username) {
        //AccountVO accountVO = (AccountVO) session.getAttribute("loginAccount");
        AccountVO loginAccount = accountService.getAccountVOByUsername(username);
        return CommonResponse.createForSuccess(ResponseCode.UserGetSuccess.getCode(), ResponseCode.UserGetSuccess.getDescription(),loginAccount);
    }

    @PostMapping("/accounts")
    public CommonResponse confirmPassword(@RequestParam String username, @RequestParam String password) {
        AccountVO accountVO = accountService.getAccountVOByUsername(username);
        System.out.println(accountVO.getPwdHash());
        if (!encryptUtil.verifyPwd(password, accountVO.getPwdHash())) {
            return CommonResponse.createForError(ResponseCode.UserPasswordIncorrectSuccess.getCode(), ResponseCode.UserPasswordIncorrectSuccess.getDescription());
        } else {
            return CommonResponse.createForSuccess(ResponseCode.UserPasswordCorrectSuccess.getCode(), ResponseCode.UserPasswordCorrectSuccess.getDescription());
        }
    }

    @PatchMapping("/accounts")
    public CommonResponse changePassword(@RequestParam String username, @RequestParam String password) {
        accountService.changePassword(username, password);
        return CommonResponse.createForSuccess(ResponseCode.UserPasswordChangeSuccess.getCode(), ResponseCode.UserPasswordChangeSuccess.getDescription());
    }
}
